<template>
  <a-modal
    v-model:open="visible"
    title="编辑管理员"
    ok-text="确认"
    cancel-text="取消"
    centered
    :width="416"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <div v-else class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-form-item
          label="选择角色"
          name="roleIds"
          :rules="[{ required: true, message: '请选择角色!' }]"
        >
          <a-select
            v-model:value="formState.roleIds"
            mode="multiple"
            allow-clear
            style="width: 200px"
            placeholder="请选择角色"
            :options="roles"
          />
        </a-form-item>

        <a-form-item
          label="管理员姓名"
          name="name"
          :rules="[{ required: true, message: '请输入管理员姓名!' }]"
        >
          <a-input
            v-model:value="formState.name"
            allow-clear
            style="width: 200px"
            placeholder="请输入管理员姓名"
          />
        </a-form-item>

        <a-form-item
          label="邮箱"
          name="email"
          :rules="[{ required: true, message: '请输入管理员邮箱!' }]"
        >
          <a-input
            v-model:value="formState.email"
            allow-clear
            style="width: 200px"
            placeholder="请输入管理员邮箱"
          />
        </a-form-item>

        <a-form-item label="密码" name="password">
          <a-input-password
            v-model:value="formState.password"
            allow-clear
            autocomplete="new-password"
            style="width: 200px"
            placeholder="请输入登录密码"
          />
        </a-form-item>

        <a-form-item label="禁止登录" name="is_ban_login">
          <a-switch
            v-model:checked="switchChecked"
            @change="onSwitchChange"
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";
import { adminUser } from "@/api";

interface Props {
  id: number;
  open: boolean;
  onCancel: () => void;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel"]);

// 状态
const visible = ref(false);
const init = ref(true);
const loading = ref(false);
const roles = ref<{ label: string; value: number }[]>([]);
const switchChecked = ref(false);

const formRef = ref();
const formState = reactive<any>({
  roleIds: [] as number[],
  name: "",
  email: "",
  password: "",
  is_ban_login: 0,
});

// 监听 open 和 id
watch(
  () => props.open,
  (val) => {
    visible.value = val;
    if (val) {
      init.value = true;
      getParams();
      if (props.id !== 0) {
        getDetail();
      } else {
        resetForm();
        init.value = false;
      }
    }
  }
);

// 获取角色列表
const getParams = () => {
  adminUser.createAdminUser().then((res: any) => {
    roles.value = (res.data.roles || []).map((r: any) => ({
      label: r.name,
      value: r.id,
    }));
  });
};

// 获取详情
const getDetail = () => {
  adminUser.AdminUser(props.id).then((res: any) => {
    const user = res.data.user;
    Object.assign(formState, {
      email: user.email,
      name: user.name,
      password: "",
      is_ban_login: user.is_ban_login,
      roleIds: res.data.role_ids,
    });
    switchChecked.value = !!user.is_ban_login;
    init.value = false;
  });
};

// 重置表单
const resetForm = () => {
  Object.assign(formState, {
    email: "",
    name: "",
    password: "",
    is_ban_login: 0,
    roleIds: [],
  });
  switchChecked.value = false;
};

// 提交表单
const onFinish = () => {
  if (loading.value) return;
  loading.value = true;
  const { name, email, password, is_ban_login, roleIds } = formState;
  const req = props.id
    ? adminUser.updateAdminUser(
        props.id,
        name,
        email,
        password || "",
        is_ban_login,
        roleIds
      )
    : adminUser.storeAdminUser(
        name,
        email,
        password,
        is_ban_login,
        roleIds
      );

  req
    .then(() => {
      message.success("保存成功！");
      loading.value = false;
      handleCancel();
    })
    .catch(() => {
      loading.value = false;
    });
};

const onFinishFailed = (errorInfo: any) => {
  console.log("验证失败:", errorInfo);
};

const handleOk = () => {
  (formRef.value as any)
    .validate()
    .then(() => {
      onFinish();
    })
    .catch((error: any) => {
      console.log("验证失败", error);
    });
};

const handleCancel = () => {
  emit("cancel");
};

// switch 切换
const onSwitchChange = (val: boolean) => {
  formState.is_ban_login = val ? 1 : 0;
};
</script>
